/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.shop.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fasterxml.jackson.core.type.TypeReference;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.JsonUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.cms.entity.Article;
import com.thinkgem.jeesite.modules.cms.entity.Site;
import com.thinkgem.jeesite.modules.cms.service.FileTplService;
import com.thinkgem.jeesite.modules.cms.service.SiteService;
import com.thinkgem.jeesite.modules.cms.utils.TplUtils;
import com.thinkgem.jeesite.modules.shop.entity.Attribute;
import com.thinkgem.jeesite.modules.shop.entity.Goods;
import com.thinkgem.jeesite.modules.shop.entity.ParameterValue;
import com.thinkgem.jeesite.modules.shop.entity.Product;
import com.thinkgem.jeesite.modules.shop.entity.ShopTag;
import com.thinkgem.jeesite.modules.shop.service.AttributeService;
import com.thinkgem.jeesite.modules.shop.service.BrandService;
import com.thinkgem.jeesite.modules.shop.service.GoodsCategoryService;
import com.thinkgem.jeesite.modules.shop.service.GoodsService;
import com.thinkgem.jeesite.modules.shop.service.ParameterService;
import com.thinkgem.jeesite.modules.shop.service.ParameterValueService;
import com.thinkgem.jeesite.modules.shop.service.ProductService;
import com.thinkgem.jeesite.modules.shop.service.ShopTagService;
import com.thinkgem.jeesite.modules.shop.service.SpecificationService;

/**
 * 商品管理Controller
 * @author xxs
 * @version 2016-03-21
 */
@Controller
@RequestMapping(value = "${adminPath}/shop/goods")
public class GoodsController extends BaseController {

	@Autowired
	private GoodsService goodsService;
	@Autowired
	private ProductService productService;
	@Autowired
	private GoodsCategoryService goodsCategoryService;
	@Autowired
	private FileTplService fileTplService;
	@Autowired
   	private BrandService brandService;
	@Autowired
	private SpecificationService specificationService;
	@Autowired
	private AttributeService attributeService;
	@Autowired
   	private ParameterService parameterService ;
	@Autowired
	private SiteService siteService;
	@Autowired
   	private ParameterValueService parameterValueService;
	@Autowired
	private ShopTagService shopTagService;
	
	@ModelAttribute
	public Goods get(@RequestParam(required=false) String id) {
		Goods entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = goodsService.get(id);
		}
		if (entity == null){
			entity = new Goods();
		}
		return entity;
	}
	
	@RequiresPermissions("shop:goods:view")
	@RequestMapping(value = {"list", ""})
	public String list(Goods goods, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Goods> page = goodsService.findPage(new Page<Goods>(request, response), goods); 
		model.addAttribute("page", page);
		return "modules/shop/goodsList";
	}

	@RequiresPermissions("shop:goods:view")
	@RequestMapping(value = "selectCategory")
	public String selectCategory(Goods goods,Model model) {
		return "modules/shop/selectCategoryForm";
	}
	
	/**
	 * 商品选择列表
	 */
	@RequiresPermissions("shop:goods:view")
	@RequestMapping(value = "selectList")
	public String selectList(Goods goods, HttpServletRequest request, HttpServletResponse response, Model model) {
        list(goods, request, response, model);
		return "modules/shop/goodsSelectList";
	}
	
	@RequiresPermissions("shop:goods:view")
	@RequestMapping(value = "add")
	public String add(Goods goods,Model model) {
		String goodsCategoryId = goods.getGoodsCategory().getId();
		model.addAttribute("contentViewList",getTplContent());
		model.addAttribute("goods_DEFAULT_GOODSVIEW",Goods.DEFAULT_GOODSVIEW);
		model.addAttribute("brands", brandService.getBrandByCategoryId(goodsCategoryId));
		model.addAttribute("specifications", specificationService.getSpecificationByCategoryId(goodsCategoryId));
		model.addAttribute("parameters", parameterService.getParameterByCategoryId(goodsCategoryId));
		model.addAttribute("attributes", attributeService.getAttributeByCategoryId(goodsCategoryId));
		ShopTag shopTag = new ShopTag();
		shopTag.setType(goods.getType());
		List<ShopTag> sts = shopTagService.findList(shopTag);
		model.addAttribute("sts", sts);
		model.addAttribute("attributes", attributeService.getAttributeByCategoryId(goodsCategoryId));
		model.addAttribute("goods", goods);
		return "modules/shop/goodsAdd";
	}
	@RequiresPermissions("shop:goods:view")
	@RequestMapping(value = "form")
	public String form(Goods goods,Model model) {
		if(goods.getPvs()!=null){
			List<ParameterValue> pvList = JsonUtils.toObject(goods.getPvs(), new TypeReference<List<ParameterValue>>() {});
			goods.setParameterValues(pvList);
		}
		String goodsCategoryId = goods.getGoodsCategory().getId();
		Product product = new Product();
		product.setGoods(goods);
		List<Product> products = productService.findList(product);
		model.addAttribute("products",products);
		model.addAttribute("contentViewList",getTplContent());
		model.addAttribute("goods_DEFAULT_GOODSVIEW",Goods.DEFAULT_GOODSVIEW);
		model.addAttribute("brands", brandService.getBrandByCategoryId(goodsCategoryId));
		model.addAttribute("specifications", specificationService.getSpecificationByCategoryId(goodsCategoryId));
		model.addAttribute("parameters", parameterService.getParameterByCategoryId(goodsCategoryId));
		ShopTag shopTag = new ShopTag();
		shopTag.setType(goods.getType());
		List<ShopTag> sts = shopTagService.findList(shopTag);
		model.addAttribute("sts", sts);
		List<Attribute> list = attributeService.getAttributeByCategoryId(goodsCategoryId);
		model.addAttribute("attributes", attributeService.getAttributeByCategoryId(goodsCategoryId));
		model.addAttribute("goods", goods);
		return "modules/shop/goodsForm";
	}

	@RequiresPermissions("shop:goods:edit")
	@RequestMapping(value = "save")
	public String save(Goods goods, Model model,ProductForm productForm, ProductListForm productListForm, String goodsCategoryId, String brandId, String[] promotionIds, String[] tagIds, HttpServletRequest request, RedirectAttributes redirectAttributes) {
//		if (!beanValidator(model, goods)){
//			return form(goods, model);
//		}
		
		parameterValueService.filter(goods.getParameterValues());
		specificationService.filter(goods.getSpecificationItems());
		productService.filter(productListForm.getProductList());
		if(CollectionUtils.isNotEmpty(goods.getParameterValues())){
			String aa  = JsonUtils.toJson(goods.getParameterValues());
			System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxx"+aa);
			goods.setPvs(aa);
			
		}else{
			goods.setPvs(null);
		}
		if(CollectionUtils.isNotEmpty(goods.getSpecificationItems())){
			String ss  = JsonUtils.toJson(goods.getSpecificationItems());
			System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxx"+ss);
			goods.setSis(ss);
			
		}else{
			goods.setSis(null);
		}
		goods.removeAttributeValue();
		List<Attribute> attributes = attributeService.getAttributeListByCategoryId(goods.getGoodsCategory().getId());
		for (Attribute attribute : attributes) {
			String value = request.getParameter("attribute_" + attribute.getId());
		    String attributeValue = attributeService.toAttributeValue(attribute, value);
			goods.setAttributeValue(attribute, value);
		}
		//goods.setGoodsCategory(new GoodsCategory(goods.getGoodsCategory().getId()));
		//goods.setBrand(brandService.get(brandId));
		if (goods.getSis()!=null) {
			List<Product> products = productListForm.getProductList();
			if (CollectionUtils.isEmpty(products) ) {
				System.err.println("规格存储出错！！！表单出现空值");
			}
			goodsService.save(goods, products);
		} else {
			Product product = productForm.getProduct();
			if (product == null) {
				System.err.println("规格存储出错！！！表单出现空值");
			}
			goodsService.save(goods, product);
		}
		
		goodsService.save(goods);
		addMessage(redirectAttributes, "保存商品成功");
		return "redirect:"+Global.getAdminPath()+"/shop/goods/?repage";
	}
	
	@RequiresPermissions("shop:goods:edit")
	@RequestMapping(value = "delete")
	public String delete(Goods goods, RedirectAttributes redirectAttributes) {
		goodsService.delete(goods);
		addMessage(redirectAttributes, "删除商品成功");
		return "redirect:"+Global.getAdminPath()+"/shop/goods/?repage";
	}
	/**
	 * 获取商品展示模板
	 * @return
	 */
    private List<String> getTplContent() {
   		List<String> tplList = fileTplService.getNameListByPrefix(siteService.get(Site.getCurrentSiteId()).getSolutionPath());
   		tplList = TplUtils.tplTrim(tplList, Goods.DEFAULT_GOODSVIEW, "");
   		return tplList;
   	}
    
    public static class ProductForm {

		private Product product;

		public Product getProduct() {
			return product;
		}

		public void setProduct(Product product) {
			this.product = product;
		}

	}

	public static class ProductListForm {

		private List<Product> productList;

		public List<Product> getProductList() {
			return productList;
		}

		public void setProductList(List<Product> productList) {
			this.productList = productList;
		}

	}
}